package org.rest.job;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class EyeRestApp extends Application {

    private Label timerLabel = new Label();
    private ComboBox<String> workTimeComboBox = new ComboBox<>();
    private ComboBox<String> restTimeComboBox = new ComboBox<>();
    private ScheduledExecutorService scheduler;
    private long workEndTime;
    private long restEndTime;
    private ProgressBar progressBar = new ProgressBar();

    @Override
    public void start(Stage primaryStage) {
        VBox root = new VBox(10);
        root.setAlignment(Pos.CENTER);
        root.setStyle("-fx-font-family: 'Arial'; -fx-font-size: 14px;");

        // Initialize UI components
        initializeUIComponents();

        // Layout the controls in a horizontal box for better spacing
        HBox buttonBox = new HBox(10, createStartButton(), createStopButton());
        buttonBox.setAlignment(Pos.CENTER);

        // Add everything to the root
        root.getChildren().addAll(
            createWorkTimeControl(),
            createRestTimeControl(),
            buttonBox,
            timerLabel,
            progressBar
        );

        Scene scene = new Scene(root, 400, 250); // Adjusted scene size for better layout
        primaryStage.setTitle("Eye Rest Reminder");
        primaryStage.setScene(scene);
        primaryStage.show();

        // Start the timer with default values
        startOrResetTimer();
    }

    private void initializeUIComponents() {
        // Work Time ComboBox
        workTimeComboBox.getItems().addAll("1", "2", "10", "20", "30", "40", "50", "60");
        workTimeComboBox.setValue("40"); // Default value
        workTimeComboBox.setPrefWidth(100);
        workTimeComboBox.setStyle("-fx-alignment: CENTER;");

        // Rest Time ComboBox
        restTimeComboBox.getItems().addAll("1", "2", "5", "10");
        restTimeComboBox.setValue("5"); // Default value
        restTimeComboBox.setPrefWidth(100);
        restTimeComboBox.setStyle("-fx-alignment: CENTER;");

        // Progress Bar
        progressBar.setVisible(false); // Initially hidden
        progressBar.setStyle("-fx-accent: green; -fx-background-color: lightgray; -fx-pref-height: 20px;"); // Set progress bar color and style
        progressBar.setPrefWidth(300); // Set preferred width for the progress bar

        // Timer Label
        timerLabel.setMinWidth(300);
        timerLabel.setAlignment(Pos.CENTER);
        timerLabel.setStyle("-fx-font-size: 16px; -fx-font-weight: bold;");
    }

    private Button createStartButton() {
        Button startButton = new Button("开始/重置");
        startButton.setOnAction(e -> startOrResetTimer());
        startButton.setStyle("-fx-font-size: 14px; -fx-padding: 5px 10px;");
        return startButton;
    }

    private Button createStopButton() {
        Button stopButton = new Button("停止");
        stopButton.setOnAction(e -> stopTimer());
        stopButton.setStyle("-fx-font-size: 14px; -fx-padding: 5px 10px;");
        return stopButton;
    }

    private HBox createWorkTimeControl() {
        Label workTimeLabel = new Label("工作板块时长（分钟）:");
        workTimeLabel.setMinWidth(150);
        workTimeLabel.setAlignment(Pos.CENTER_RIGHT);
        workTimeLabel.setStyle("-fx-font-size: 14px;");
        return new HBox(10, workTimeLabel, workTimeComboBox);
    }

    private HBox createRestTimeControl() {
        Label restTimeLabel = new Label("休息时长（分钟）:");
        restTimeLabel.setMinWidth(150);
        restTimeLabel.setAlignment(Pos.CENTER_RIGHT);
        restTimeLabel.setStyle("-fx-font-size: 14px;");
        return new HBox(10, restTimeLabel, restTimeComboBox);
    }

    private void startOrResetTimer() {
        if (scheduler != null && !scheduler.isShutdown()) {
            scheduler.shutdownNow();
        }
        scheduler = Executors.newSingleThreadScheduledExecutor();

        try {
            int workTime = Integer.parseInt(workTimeComboBox.getValue());
            int restTime = Integer.parseInt(restTimeComboBox.getValue());
            long workInterval = TimeUnit.MINUTES.toMillis(workTime);
            long restInterval = TimeUnit.MINUTES.toMillis(restTime);

            long startTime = System.currentTimeMillis();
            workEndTime = startTime + workInterval;
            restEndTime = workEndTime + restInterval;

            scheduler.scheduleAtFixedRate(() -> {
                if (scheduler.isShutdown()) {
                    return;
                }
                long currentTime = System.currentTimeMillis();

                if (currentTime < workEndTime) {
                    long timeLeft = workEndTime - currentTime;
                    String message = "下一次你该在 " + formatDuration(timeLeft) + " 休息 " + restTime + " 分钟";
                    updateUI(message, (double) timeLeft / workInterval, true);
                } else if (currentTime < restEndTime) {
                    long timeLeft = restEndTime - currentTime;
                    String message = "休息时间：" + formatDuration(timeLeft);
                    updateUI(message, (double) timeLeft / restInterval, true);
                } else {
                    // Reset the timer
                    workEndTime = currentTime + workInterval;
                    restEndTime = workEndTime + restInterval;
                    updateUI("工作时间：00:00", 0, false);
                }
            }, 0, 1000, TimeUnit.MILLISECONDS);
        } catch (NumberFormatException e) {
            updateLabel("请输入有效的分钟数！");
        }
    }

    private void stopTimer() {
        if (scheduler != null && !scheduler.isShutdown()) {
            scheduler.shutdownNow();
            updateUI("计时器已停止", 0, false);
        }
    }

    private String formatDuration(long millis) {
        long seconds = TimeUnit.MILLISECONDS.toSeconds(millis) % 60;
        long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
        return String.format("%02dmin %02ds", minutes, seconds);
    }

    private void updateUI(String message, double progress, boolean showProgressBar) {
        Platform.runLater(() -> {
            updateLabel(message);
            progressBar.setProgress(progress);
            progressBar.setVisible(showProgressBar);
        });
    }

    private void updateLabel(String text) {
        timerLabel.setText(text);
    }

    public static void main(String[] args) {
        launch(args);
    }
}
